@extends('admin.main')

@section('content')
<div class="wrapper wrapper-content">
	<div class="ibox">
		<div class="ibox-title">
			<h5>链接列表</h5>
		</div>
		<div class="ibox-content">
			<div class="m-b">
				<a href="javascript:;" id="btnAdd" class="btn btn-w-m btn-warning m-r-xs"><i class="fa fa-plus"></i> 添加链接</a>
				<a href="javascript:;" id="btnDel" class="btn btn-danger"><i class="fa fa-trash"></i> 删除</a>
			</div>
			<div class="table-responsive">
				<table id="tblDataList" class="table table-striped">
					<thead>
						<tr>
							<th width="50"><input type="checkbox" id="checkAll" title="全选" /></th>
							<th>名称</th>
							<th>链接</th>
							<th>标签</th>
							<th>图片</th>
							<th width="100"></th>
						</tr>
					</thead>
					<tbody>
						@foreach($links as $row)
						<tr data-id="{{$row->id}}">
							<td>
								<input type="checkbox" name="ids" value="{{$row->id}}" />
							</td>
							<td>{{$row->name}}</td>
							<td><a href="{{$row->url}}" target="_blank">{{$row->url}}</a></td>
							<td>
								@foreach ($row->tags as $tag)
								<label class="label">{{$tag->tag}}</label>
								@endforeach
							</td>
							<td>
								<a href="javascript:;" class="m-r-xs js-pic" data-src="{{$row->pic ? url($row->pic) : ''}}">
									@if(empty($row->pic))
									<i class="fa fa-cloud-upload fa-lg"></i>
									@else
									<i class="fa fa-file-image-o fa-lg"></i>
									@endif
								</a>
							</td>
							<td>
								<a href="javascript:;" class="m-r-xs js-edit">
									<i class="fa fa-pencil-square fa-lg"></i> 编辑
								</a>
							</td>
						</tr>
						@endforeach
					</tbody>
				</table>
				<div class="text-center"><?php echo $links->render();?></div>
			</div>
		</div>
	</div>
</div>

<script id="tplDataListTr" type="text/html">
	<tr data-id="<%id%>">
		<td>
			<input type="checkbox" name="ids" value="<%id%>" />
		</td>
		<td><%name%></td>
		<td><a href="<%url%>" target="_blank"><%url%></a></td>
		<td>
			<%each tags as row i%>
			<label class="label"><%row.tag%></label>
			<%/each%>
		</td>
		<td>
			<a href="javascript:;" class="m-r-xs js-pic" data-src="<%src%>">
				<%if src%>
				<i class="fa fa-file-image-o fa-lg"></i>
				<%else%>
				<i class="fa fa-cloud-upload fa-lg"></i>
				<%/if%>
			</a>
		</td>
		<td>
			<a href="javascript:;" class="m-r-xs js-edit">
				<i class="fa fa-pencil-square fa-lg"></i> 编辑
			</a>
		</td>
	</tr>
</script>

<div id="myAddModal" class="modal fade" aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<form id="formAdd" method="post" action="{{url('admin/link/insert')}}" class="form-horizontal">
				<div class="modal-header">
					<button class="close" data-dismiss="modal" type="button">&times;</button>
					<h4 class="modal-title" id="avatar-modal-label">添加</h4>
				</div>
				<div class="modal-body">
					<div class="form-group">
						<label class="col-sm-2 control-label">名称</label>
						<div class="col-sm-5">
							<input type="text" name="name" class="form-control" required="" autofocus>
						</div>
					</div>
					<div class="hr-line-dashed"></div>
					<div class="form-group">
						<label class="col-sm-2 control-label">链接</label>
						<div class="col-sm-10">
							<input type="text" name="url" class="form-control" required="">
						</div>
					</div>
					<div class="hr-line-dashed"></div>
					<div class="form-group">
						<label class="col-sm-2 control-label">标签</label>
						<div class="col-sm-10">
							@foreach($tags as $row)
							<div class="checkbox-inline i-checks"><label><input type="checkbox" name="tag_id[]" value="{{$row->id}}"> {{$row->tag}}</label></div>
							@endforeach
						</div>
					</div>
					<div class="hr-line-dashed"></div>
					<div class="form-group">
						<div class="col-sm-4 col-sm-offset-2">
							<input type="hidden" name="_token" value="{{ csrf_token() }}">
							<button class="btn btn-primary btn-w-m" type="submit">提交</button>
						</div>
					</div>
				</div>
  		</form>
  	</div>
  </div>
</div>

<div id="myEditModal" class="modal fade" aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1"></div>
<script id="tplEditPannel" type="text/html">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<form id="formEdit" method="post" action="{{url('admin/link/update')}}" class="form-horizontal">
				<div class="modal-header">
					<button class="close" data-dismiss="modal" type="button">&times;</button>
					<h4 class="modal-title" id="avatar-modal-label">编辑</h4>
				</div>
				<div class="modal-body">
					<div class="form-group">
						<label class="col-sm-2 control-label">名称</label>
						<div class="col-sm-5">
							<input type="text" name="name" value="<%name%>" class="form-control" required="" autofocus>
						</div>
					</div>
					<div class="hr-line-dashed"></div>
					<div class="form-group">
						<label class="col-sm-2 control-label">链接</label>
						<div class="col-sm-10">
							<input type="text" name="url" value="<%url%>" class="form-control" required="">
						</div>
					</div>
					<div class="hr-line-dashed"></div>
					<div class="form-group">
						<label class="col-sm-2 control-label">标签</label>
						<div class="col-sm-10">
							@foreach($tags as $row)
							<div class="checkbox-inline i-checks"><label><input type="checkbox" name="tag_id[]" value="{{$row->id}}"<%'{{$row->tag}}' | inArray:tags%>> {{$row->tag}}</label></div>
							@endforeach
						</div>
					</div>
					<div class="hr-line-dashed"></div>
					<div class="form-group">
						<div class="col-sm-4 col-sm-offset-2">
							<input type="hidden" name="id"  value="<%id%>">
							<button class="btn btn-primary btn-w-m" type="submit">提交</button>
						</div>
					</div>
				</div>
  		</form>
  	</div>
  </div>
</script>

<div id="myUploadPicModal" class="modal fade" aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1"></div>
<script id="tplUploadPic" type="text/html">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<div class="modal-header">
				<button class="close" data-dismiss="modal" type="button">&times;</button>
				<h4 class="modal-title" id="avatar-modal-label">图片上传</h4>
			</div>
			<div class="modal-body">
				<form id="formUppic" method="post" enctype="multipart/form-data" action="{{url('admin/link/upload-pic')}}" class="form-horizontal">
					<div class="form-group">
						<label class="col-sm-2 control-label">选择图片</label>
						<div class="col-sm-5">
							<input name="pic" type="file" class="form-control" />
						</div>
					</div>
					<div class="form-group">
						<label class="col-sm-2 control-label">缩略图</label>
						<div class="col-sm-3">
							<div class="input-group">
								<div class="input-group-addon">宽</div>
								<input type="text" name="thumb_width" value="200" class="form-control" onkeyup="value=value.replace(/[^\d]/g,'');" />
								<div class="input-group-addon">px</div>
							</div>
						</div>
						<div class="col-sm-3">
							<div class="input-group">
								<div class="input-group-addon">高</div>
								<input type="text" name="thumb_height" value="200" class="form-control" onkeyup="value=value.replace(/[^\d]/g,'');" />
								<div class="input-group-addon">px</div>
							</div>
						</div>
					</div>
					<div class="form-group">
						<div class="col-sm-10 col-sm-offset-2">
							<input type="hidden" name="id"  value="<%id%>">
							<button class="btn btn-primary btn-w-m" type="submit"><i class="fa fa-cloud-upload fa-lg"></i> 上传图片</button>
							<button class="btn btn-danger m-l" type="button" onclick="deletePic(<%id%>)"><i class="fa fa-times fa-lg"></i> 删除图片</button>
						</div>
					</div>
					<div class="hr-line-dashed"></div>
					<div class="form-group">
						<label class="col-sm-2 control-label">预览</label>
						<div id="pictureViewer" class="col-sm-10">
							<%if src%>
		  				<img src="<%src%>" class="img-thumbnail" />
		  				<%else%>
		  				<img src="/assets/images/blank.gif" class="img-thumbnail" />
		  				<%/if%>
						</div>
					</div>
	  		</form>
			</div>
  	</div>
  </div>
</script>
@endsection

@section('pageheader')
<link href="{{asset('assets/css/plugins/iCheck/custom.css')}}" rel="stylesheet">
@endsection

@section('pagescript')
<script src="{{asset('assets/js/plugins/iCheck/icheck.min.js')}}"></script>
<script>
	$("#sidebar li[rel='link']").addClass("active")
		.find("ul").addClass("in")
		.find("li[rel='1']").addClass("active");

	$('.i-checks').iCheck({
    checkboxClass: 'icheckbox_square-green',
    radioClass: 'iradio_square-green',
  });

	$('#checkAll').click(function(){
		var checked = $(this).prop("checked");
		$("#tblDataList tr[data-id] :checkbox").each(function(){
			$(this).prop("checked", checked);
		});
	}).tooltip({placement: 'right'});

	$("#btnAdd").on('click', function(){
		$("#myAddModal").modal('show');
	});

	$("#formAdd").on('submit', function(){
		var form = this;
		$.ajax(this.action, {
      type: 'post',
      data: $(this).serialize(),
      dataType: 'json',
      beforeSend: function () {
        $("#loadingMask").fadeIn();
      },
      success: function (result) {
      	$(form).find('.i-checks').iCheck('uncheck');
      	form.reset();
      	var html = template('tplDataListTr', result);
      	$("#tblDataList tr").eq(0).after(html);
      	$("#myAddModal").modal('hide');
      },
      complete: function () {
        $("#loadingMask").fadeOut();
      },
      error: failure
    });
		return false;
	});

	$("#myEditModal").delegate('#formEdit', 'submit', function(){
		var form = this;
		$.ajax(this.action, {
      type: 'post',
      data: $(this).serialize(),
      dataType: 'json',
      beforeSend: function () {
        $("#loadingMask").fadeIn();
      },
      success: function (result) {
      	var tr = $("#tblDataList").find("tr[data-id='"+ result.id +"']").eq(0);
      	var html = template('tplDataListTr', result);
      	tr.after(html).remove();
      	$("#myEditModal").modal('hide');
      },
      complete: function () {
        $("#loadingMask").fadeOut();
      },
      error: failure
    });
		return false;
	});

	$("#tblDataList").delegate('.js-edit', 'click', function(){
		var tr = $(this).parents('tr').eq(0),
				id = tr.data('id'),
				name = tr.find('td').eq(1).text(),
				url = tr.find('td').eq(2).text();
		var tags = new Array();
		tr.find('td').eq(3).find('.label').each(function(){
			tags.push($(this).text());
		});
		template.helper('inArray', function(val, arr){
			return ($.inArray(val, arr) == -1) ? '' : 'checked';
		});
		var html_str = template('tplEditPannel', {'id':id,'name':name,'url':url,'tags':tags});
		$("#myEditModal").html(html_str).modal('show');
		$("#myEditModal").find('.i-checks').iCheck({
	    checkboxClass: 'icheckbox_square-green',
	    radioClass: 'iradio_square-green',
	  });
	});

	$("#tblDataList").delegate('.js-pic', 'click', function(){
		var data = {
			'id': $(this).parents('tr').eq(0).data("id"),
			'src': $(this).data("src")
		};
		$("#myUploadPicModal").html(template("tplUploadPic", data)).modal('show');
	});

	$("#myUploadPicModal").delegate("#formUppic", 'submit', function(){
		var url = $(this).attr("action"),
				id = this.id.value,
				file = this.pic.value;
		if (file == ""){
			alert("请选择上传文件！");
			return false;
		}
		if (file.lastIndexOf(".") == -1){
			alert("文件类型不正确！");
			return false;
		}
		var ext = file.substr(file.lastIndexOf(".") + 1).toLowerCase();
		if (ext != 'jpg' && ext != 'gif' && ext != 'png'){
			alert('图片必须是 JPG、GIF 或者 PNG 格式！');
			return false;
		}
		if ( ! /^[1-9]\d{0,3}$/.exec(this.thumb_width.value)){
			alert("宽度只能使用1-4位数字！");
			this.thumb_width.focus();
			return false;
		}
		if ( ! /^[1-9]\d{0,3}$/.exec(this.thumb_height.value)){
			alert("高度只能使用1-4位数字！");
			this.thumb_height.focus();
			return false;
		}
		var data = new FormData();
		data.append('id', this.id.value);
		data.append('pic', this.pic.files[0]);
		data.append('width', this.thumb_width.value);
		data.append('height', this.thumb_height.value);
		$.ajax(url, {
      type: "post",
      data: data,
      dataType: 'json',
      processData: false,
      contentType: false,
      beforeSend: function () {
        $("#loadingMask").fadeIn();
      },
      success: function (result) {
      	$("#pictureViewer img").eq(0).attr("src", result);
      	var tr = $("#tblDataList").find("tr[data-id='"+ id +"']").eq(0),
      			ta = tr.find(".js-pic").eq(0);
      	ta.data("src", result);
      	ta.find("i").removeClass("fa-cloud-upload").addClass("fa-file-image-o");
      },
      complete: function () {
        $("#loadingMask").fadeOut();
      },
      error: failure
    });
		return false;
	});

	$("#btnDel").on('click', function(){
		var keys = Array();
		$("input[name='ids']").each(function(){
			if(this.checked){
				keys.push($(this).val());
			}
		});
		var keyValue = keys.join("|");
		if(keyValue){
			dialog({
				content: '<i class="fa fa-info-circle"></i> 即将删除所选择的 <b>'+ keys.length +'</b> 条记录, 且该操作不能恢复! 是否继续 ?',
				ok: function(){
					$.post('/admin/link/delete', {"ids":keyValue}, function(data){
						$("tr[data-id]").each(function(){
							if($(this).find("input[name='ids']").prop("checked")){
								$(this).remove();
							}
						});
						$("#checkAll").prop("checked", false);
					}).fail(failure);
				},
				cancel: true
			}).showModal();
		}else{
			failure('请先选择准备删除的记录！');
		}
	});

	var deletePic = function(id){
		if(confirm("确定要删除此图片吗？")){
			$.post('/admin/link/delete-pic', {"id":id}, function(data){
				$("#pictureViewer img").eq(0).attr("src", "/assets/images/blank.gif");
      	var tr = $("#tblDataList").find("tr[data-id='"+ id +"']").eq(0),
      			ta = tr.find(".js-pic").eq(0);
      	ta.data("src", "");
      	ta.find("i").removeClass("fa-file-image-o").addClass("fa-cloud-upload");
			}).fail(failure);
		}
	};
</script>
@endsection